package mo.tags.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class StackOfPlates {

    private int cap;
    private List<Stack<Integer>> stackList = new ArrayList<>();

    public StackOfPlates(int cap) {
        this.cap = cap;
    }

    public void push(int val) {
        if (cap == 0) {
            return;
        }
        if (stackList.isEmpty() || stackList.get(stackList.size()-1).size() == cap) {
            Stack<Integer> stack = new Stack<>();
            stack.push(val);
            stackList.add(stack);
            return;
        }
        Stack<Integer> stack = stackList.get(stackList.size() - 1);
        stack.push(val);
    }

    public int pop() {
        return popAt(stackList.size()-1);
    }

    public int popAt(int index) {
        if (index < 0 || index >= stackList.size()) {
            return -1;
        }
        Stack<Integer> stack = stackList.get(index);
        int val = stack.pop();
        if (stack.size() == 0) {
            stackList.remove(index);
        }
        return val;
    }

    public static void main(String[] args) {
        StackOfPlates test = new StackOfPlates(1);
        test.push(1);
        test.push(2);
        System.out.println(test.pop());
        System.out.println(test.pop());
        System.out.println(test.pop());
        System.out.println(test.pop());
    }

}
